
import { EditOutlined} from '@ant-design/icons';
import { Avatar, Card, Button, Form, Input, Space, Modal, Upload, UploadProps, message } from 'antd';
import React, { useEffect, useState } from 'react';
import { useModel } from '@umijs/max';
import {updateMyUserAvatarPost,updateMyUserUsingPost,updateMyUserPswPost} from '@/services/backend/userController';
import { UploadOutlined } from '@ant-design/icons';
import { SUCCESS_CODE } from '@/constants/index';

const tabList = [
{
    key: '基本资料',
    tab: '基本资料',
},
{
    key: '修改密码',
    tab: '修改密码',
},
];
const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
};
const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
};
export default () => {
    const { Meta } = Card;
    const { initialState, setInitialState } = useModel('@@initialState');
    const [activeTabKey, setActiveTabKey] = useState<string>('基本资料');
    const [previewVisible, setPreviewVisible] = useState(false);//图片预览
    const [previewImage, setPreviewImage] = useState({//预览图片路径
        url: '', 
        file: null
    });
    const [form] = Form.useForm();
    const userAvatar = initialState?.currentUser?.userAvatar;//用户头像
    const userAccount = initialState?.currentUser?.userAccount;//用户名
    const userProfile = initialState?.currentUser?.userProfile;//用户个人简介

    const onTabChange = (key: string) => {
        setActiveTabKey(key);
    }
    useEffect(()=>{
        form.setFieldsValue({userAvatar,userAccount,userProfile});
    })
    //修改用户信息
    const onFinishInfor = async(values: any) => {
        const res = await updateMyUserUsingPost(values)
        setInitialState({
            ...initialState,
            currentUser:{
              ...res.data,
            }
          });
        if(res.code === SUCCESS_CODE){
            message.success(res.message)
        }
    };
    //修改密码
    const onFinishPassword = async(values: any) => {          
          const psw = {
            oldPassword:values.oldPassword,
            newPassword:values.newPassword
          }
        const res = await updateMyUserPswPost({...psw});
        if(res.code === SUCCESS_CODE){
            message.success(res.message)
            form.resetFields();
        }
    };
    //表格重置
    const onReset = () => {
        form.resetFields();
    };
    //图片上传配置
    const props: UploadProps = {
        listType:"picture" ,
        maxCount:1,
        showUploadList:false,
        onChange:(info)=>{
            const reader = new FileReader();
            reader.readAsDataURL(info.file.originFileObj);
            reader.onload = (e) => {
                setPreviewImage({
                    url:e.target.result,
                    file:info.file.originFileObj
                });
            };
        },
    };
    // 修改用户头像
    const handleImageUpload = async()=>{
        const formData = new FormData();
        formData.append('file',previewImage.file);
        const res = await updateMyUserAvatarPost(formData);
        if(res.code === SUCCESS_CODE){
            message.success("用户头像修改成功")
            setPreviewVisible(false);
            setInitialState({
                ...initialState,
                currentUser:{
                    ...initialState?.currentUser,
                    userAvatar:res.data
                }
              });
        }
    }
    const contentList: Record<string, React.ReactNode> = {
    基本资料:  
            <Form
                {...layout}
                form={form}
                name="control-hooks"
                onFinish={onFinishInfor}
                style={{ maxWidth: 600 }}
                >
                <Form.Item name="userAccount" label="用户昵称" rules={[{ required: true },{min:2}]}>
                    <Input value={userAccount}/>
                </Form.Item>
                <Form.Item name="userProfile" label="个人简介">
                    <Input value={userProfile}/>
                </Form.Item>
                <Form.Item {...tailLayout}>
                    <Space>
                        <Button type="primary" htmlType="submit">保存</Button>
                        <Button htmlType="button" onClick={onReset}>Reset</Button>                    
                    </Space>
                </Form.Item>
            </Form>,
    修改密码: 
        <Form
            {...layout}
            form={form}
            name="control-hooks"
            onFinish={onFinishPassword}
            style={{ maxWidth: 600 }}
            >
            <Form.Item
                name="oldPassword"
                label="旧密码"
                rules={[
                {
                    required: true,
                    message: '请输入原密码!',
                },
                {
                    min: 8,
                    type: 'string',
                    message: '长度不能小于 8',
                },
                ]}
                hasFeedback
            >
                <Input.Password />
            </Form.Item>
                <Form.Item
                name="newPassword"
                label="新密码"
                rules={[
                {
                    required: true,
                    message: '请输入新修改的密码！',
                },
                {
                    min: 8,
                    type: 'string',
                    message: '长度不能小于 8',
                },
                ]}
                hasFeedback
            >
                <Input.Password />
            </Form.Item>
            <Form.Item
                name="newPassword1"
                label="确认密码"
                dependencies={['newPassword']}
                hasFeedback
                rules={[
                {
                    required: true,
                    message: '请确认新修改的密码！',
                },
                ({ getFieldValue }) => ({
                    validator(_, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                        return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致！'));
                    },
                }),
                ]}
            >
                <Input.Password />
            </Form.Item>
            <Form.Item {...tailLayout}>
                <Space>
                    <Button type="primary" htmlType="submit">保存</Button>
                    <Button htmlType="button" onClick={onReset}>重置</Button>                    
                </Space>
            </Form.Item>
        </Form>,
    };

    return (
        <div style={{display:'flex'}}>
            <Card
                style={{ width: 300,marginRight:30 }}
                cover={
                <img
                    alt="example"
                    src={userAvatar}
                />
                }
                actions={[
                    <EditOutlined 
                        key="edit"
                        onClick={() => {
                            setPreviewVisible(true);
                            setPreviewImage((preState)=>{
                                const newState = {
                                    ...preState,
                                    url:userAvatar
                                }
                                return newState;
                            });
                        }} />,
                ]}
                >
                <Meta
                    avatar={<Avatar src={userAvatar} />}
                    title={userAccount}
                    description={userProfile?userProfile:'主人很懒，什么都没留下'}
                />
            </Card>
            <Card
                style={{ width: '100%' }}
                title='基本资料'
                tabList={tabList}
                activeTabKey={activeTabKey}
                onTabChange={onTabChange}
            >
                {contentList[activeTabKey]}
            </Card>
            <Modal open={previewVisible} footer={null} closable={false} onCancel={() => setPreviewVisible(false)}>
                <img src={previewImage.url || userAvatar} alt="Preview" style={{ width: '100%' }} />
                <div style={{display:'flex',justifyContent:'space-between',marginTop:20}}>
                    <Upload {...props}>
                        <Button icon={<UploadOutlined />}>Select File</Button>
                    </Upload>
                    <Button onClick={handleImageUpload}>上传图片</Button>
                </div> 
            </Modal>
        </div>
    );
};
